import { useState, useEffect, useCallback } from 'react';
import { login, verifyToken, getCaptcha } from '../request/auth';

const useAuth = () => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(true);
  const [captcha, setCaptcha] = useState<string>('');

  const refreshCaptcha = useCallback(async () => {
    const newCaptcha = await getCaptcha();
    setCaptcha(newCaptcha);
  }, []);

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const token = localStorage.getItem('token');
        if (token) {
          const isValid = await verifyToken();
          setIsAuthenticated(isValid);
        }
      } catch (error) {
        setIsAuthenticated(false);
      } finally {
        setLoading(false);
      }
    };

    checkAuth();
    refreshCaptcha();
  }, [refreshCaptcha]);

  const handleLogin = async (username: string, password: string, captchaText: string) => {
    try {
      const { token } = await login({ username, password, captcha: captchaText });
      localStorage.setItem('token', token);
      setIsAuthenticated(true);
      return { success: true };
    } catch (error) {
      await refreshCaptcha();
      throw error;
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    setIsAuthenticated(false);
    refreshCaptcha();
  };

  return {
    isAuthenticated,
    loading,
    captcha,
    refreshCaptcha,
    login: handleLogin,
    logout: handleLogout,
  };
};

export default useAuth;